package log

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"lib/config"
	"lib/directory"
	"os"
	"time"
)

var logger *zap.Logger

func InitZap(lcf *config.Zap) error {
	ok, err := directory.PathExists(lcf.Director, false)
	if err != nil {
		return err
	}
	if !ok { // 判断是否有Director文件夹
		fmt.Printf("create %v directory\n", lcf.Director)
		err = os.Mkdir(lcf.Director, os.ModePerm)
		if err != nil {
			return err
		}
	}
	// 调试级别
	debugPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev == zap.DebugLevel
	})
	// 日志级别
	infoPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev == zap.InfoLevel

	})
	// 警告级别
	warnPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev == zap.WarnLevel
	})
	// 错误级别
	errorPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev >= zap.ErrorLevel
	})

	cores := [...]zapcore.Core{
		getEncoderCore(lcf, fmt.Sprintf("./%s/server_debug.log", lcf.Director), debugPriority),
		getEncoderCore(lcf, fmt.Sprintf("./%s/server_info.log", lcf.Director), infoPriority),
		getEncoderCore(lcf, fmt.Sprintf("./%s/server_warn.log", lcf.Director), warnPriority),
		getEncoderCore(lcf, fmt.Sprintf("./%s/server_error.log", lcf.Director), errorPriority),
	}
	logger = zap.New(zapcore.NewTee(cores[:]...), zap.AddCaller(), zap.AddCallerSkip(1))

	if lcf.ShowLine {
		logger = logger.WithOptions(zap.AddCaller())
	}
	return nil
}

// getEncoderConfig 获取zapcore.EncoderConfig
func getEncoderConfig(lcf *config.Zap) (config zapcore.EncoderConfig) {
	config = zapcore.EncoderConfig{
		MessageKey:     "message",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "logger",
		CallerKey:      "caller",
		StacktraceKey:  lcf.StacktraceKey,
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     CustomTimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
	}
	switch lcf.EncodeLevel {
	case "LowercaseColorLevelEncoder": // 小写编码器带颜色
		config.EncodeLevel = zapcore.LowercaseColorLevelEncoder
	case "CapitalLevelEncoder": // 大写编码器
		config.EncodeLevel = zapcore.CapitalLevelEncoder
	case "CapitalColorLevelEncoder": // 大写编码器带颜色
		config.EncodeLevel = zapcore.CapitalColorLevelEncoder
	}
	return config
}

// getEncoder 获取 zapcore.Encoder
func getEncoder(lcf *config.Zap) zapcore.Encoder {
	if lcf.Format == "json" {
		return zapcore.NewJSONEncoder(getEncoderConfig(lcf))
	}
	return zapcore.NewConsoleEncoder(getEncoderConfig(lcf))
}

// getEncoderCore 获取Encoder的 zapcore.Core
func getEncoderCore(lcf *config.Zap, fileName string, level zapcore.LevelEnabler) (core zapcore.Core) {
	writer := GetWriteSyncer(fileName) // 使用file-rotatelogs进行日志分割
	return zapcore.NewCore(getEncoder(lcf), writer, level)
}

// CustomTimeEncoder 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	//enc.AppendString(t.Format(lcf.Prefix + "2006/01/02 - 15:04:05.000"))
	enc.AppendString(t.Format("2006/01/02 - 15:04:05.000"))
}

func GetWriteSyncer(file string) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   file, //日志文件的位置
		MaxSize:    10,   //在进行切割之前，日志文件的最大大小（以MB为单位）
		MaxBackups: 200,  //保留旧文件的最大个数
		MaxAge:     30,   //保留旧文件的最大天数
		Compress:   true, //是否压缩/归档旧文件
	}
	return zapcore.AddSync(lumberJackLogger)
}

func Debug(msg string, fields ...zap.Field) {
	logger.Debug(msg, fields...)
}

func Debugf(format string, args ...any) {
	logger.Debug(fmt.Sprintf(format, args...))
}

func Info(msg string, fields ...zap.Field) {
	logger.Info(msg, fields...)
}

func Infof(format string, args ...any) {
	logger.Info(fmt.Sprintf(format, args...))
}

func Warn(msg string, fields ...zap.Field) {
	logger.Warn(msg, fields...)
}

func Warnf(format string, args ...any) {
	logger.Warn(fmt.Sprintf(format, args...))
}

func Error(msg string, fields ...zap.Field) {
	logger.Error(msg, fields...)
}

func Errorf(format string, args ...any) {
	logger.Error(fmt.Sprintf(format, args...))
}

func DPanic(msg string, fields ...zap.Field) {
	logger.DPanic(msg, fields...)
}

func DPanicf(format string, args ...any) {
	logger.DPanic(fmt.Sprintf(format, args...))
}

func Panic(msg string, fields ...zap.Field) {
	logger.Panic(msg, fields...)
}

func Panicf(format string, args ...any) {
	logger.Panic(fmt.Sprintf(format, args...))
}

func Fatal(msg string, fields ...zap.Field) {
	logger.Fatal(msg, fields...)
}

func Fatalf(format string, args ...any) {
	logger.Fatal(fmt.Sprintf(format, args...))
}
